/**
 * 
 */
package com.pactera.android.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

/**
 * @author David Zheng
 *
 */
public class HttpUtil {
	
	static final String TAG = "HttpUtil";
	
	public static HttpClient httpClient = new DefaultHttpClient();
	
	public static String postRequest(String url, Map<String, String>rawParams) throws Exception{
		StringBuilder result = new StringBuilder();
		HttpPost post = new HttpPost(url);
		if (rawParams != null) {
			List<NameValuePair> params = new ArrayList<NameValuePair>();
			for (String key : rawParams.keySet()) {
				params.add(new BasicNameValuePair(key, rawParams.get(key)));
			}
			post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
		}
		
		post.addHeader("Accept", "application/json");

		HttpResponse httpResponse = httpClient.execute(post);

		if (200 == httpResponse.getStatusLine().getStatusCode()) {			
			 //result = EntityUtils.toString(httpResponse.getEntity());
			InputStream content = httpResponse.getEntity().getContent();
	        BufferedReader reader = new BufferedReader(new InputStreamReader(content));
	        String line;
	        while ((line = reader.readLine()) != null) {
	        	result.append(line);
	        }
		}

		return result.toString();

	}

}
